package cn.bugstack.infrastructure.adapter.repository;

import cn.bugstack.infrastructure.adapter.dcc.DCCService;
import cn.bugstack.infrastructure.redis.IRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.function.Supplier;


/**
 * @author liuxinzhi
 * @description: 抽象类用于redis降级数据库处理
 * @date 2025/8/18 14:51
 */
public abstract class AbstractRepository {
    private final Logger logger = LoggerFactory.getLogger(AbstractRepository.class);

    @Resource
    protected DCCService dccService;

    @Resource
    protected IRedisService redisService;


    protected <T> T getValueByCacheOrDb(String cacheKey, Supplier<T> dbFallback){
        if(dccService.isCacheOpenSwitch()){// 是否开启缓存
            T cacheValue = redisService.getValue(cacheKey);
            if(null != cacheValue){
                return cacheValue;
            }
            T dbValue = dbFallback.get();
            if(null == dbValue){
                return null;
            }
            redisService.setValue(cacheKey, dbValue);
            return dbValue;
        }else {
            return dbFallback.get();
        }
    }
}
